package com.liangsui.mss.component.shiro;

import com.liangsui.mss.domain.User;
import com.liangsui.mss.service.UserService;
import com.liangsui.mss.vo.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * UserRealm
 *
 * @author zhangjiawei
 * @email 1533167396@qq.com
 * @date 2022/12/3 16:25
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 认证 -- 登录
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1.得到用户名
        String phone = (String) authenticationToken.getPrincipal();
        // 2.根据电话查询用户是否存在
        User user = userService.queryUserByPhone(phone);
        // 3.判断用户是否存在
        if (null != user) {
            // 4.根据用户id查询用户角色
            // 5.根据用户id查询权限
            // 6.组装数据
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    activerUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName()
            );

            return info;
        }
        return null;
    }

    /**
     * 授权 -- 登录之后判断某个用户是否拥有某个菜单和按钮的权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取角色权限
        ActiverUser activerUser = (ActiverUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

//    @Override
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        // 构建凭证匹配对象
//        HashedCredentialsMatcher cMatcher = new HashedCredentialsMatcher();
//        // 设置加密算法  Matcher
//        cMatcher.setHashAlgorithmName("MD5");
//        // 设置加密次数
//        cMatcher.setHashIterations(2);
//        super.setCredentialsMatcher(cMatcher);
//    }
}
